/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ChequeDialog.java
 *
 * Created on Nov 23, 2010, 10:04:46 AM
 */
package br.com.tbp.gui;

import br.com.tbp.controle.ControleSupervisor;
import br.com.tbp.controle.ControleEndereco;
import br.com.tbp.exception.InputValidationException;
import br.com.tbp.exception.PersistenciaException;
import br.com.tbp.model.domain.Supervisor;
import br.com.tbp.model.domain.Endereco;
import br.com.tbp.model.domain.Foto;
import br.com.tbp.utils.DateUtils;
import br.com.tbp.utils.ImageFilter;
import br.com.tbp.utils.ImageUtils;
import com.towel.swing.img.JImagePanel;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.UIManager;

/**
 *
 * @author Diego Freire
 */
public class SupervisorDialog extends javax.swing.JDialog {

    private JButton buscarCepButton;
    private boolean refresh = false;
    private MenuPrincipal menu;
    private JFileChooser fc;
    private JImagePanel jImagePanel = null;
    private Foto foto = null;
    private boolean novoSupervisor;
    private Supervisor supervisor;

    public SupervisorDialog(java.awt.Frame parent, String name, boolean modal) {
        super(parent, name, modal);
        initComponents();
        if (parent instanceof MenuPrincipal) {
            this.menu = (MenuPrincipal) parent;
        }
        cepTextField.add(getCepButton(), "After");
        setLocationRelativeTo(null);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel9 = new javax.swing.JPanel();
        msgLabel = new javax.swing.JLabel();
        jPanel10 = new javax.swing.JPanel();
        ativoCheckBox = new javax.swing.JCheckBox();
        jPanel2 = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        idTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        nomeTextField = new javax.swing.JTextField();
        jLabel14 = new javax.swing.JLabel();
        cpfTextField = new javax.swing.JFormattedTextField();
        jLabel15 = new javax.swing.JLabel();
        dataAniversarioTextField = new javax.swing.JFormattedTextField();
        jLabel3 = new javax.swing.JLabel();
        telefone1TextField = new javax.swing.JFormattedTextField();
        jLabel4 = new javax.swing.JLabel();
        telefone2TextField = new javax.swing.JFormattedTextField();
        jLabel12 = new javax.swing.JLabel();
        emailTextField = new javax.swing.JTextField();
        jLabel16 = new javax.swing.JLabel();
        rgTextField = new javax.swing.JTextField();
        jPanel7 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        logradouroTextField = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        complementoTextField = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        cepTextField = new javax.swing.JFormattedTextField();
        estadoTextField = new javax.swing.JFormattedTextField();
        bairroTextField = new javax.swing.JTextField();
        cidadeTextField = new javax.swing.JTextField();
        jPanel8 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        scrollpane = new javax.swing.JScrollPane();
        obsTextArea = new javax.swing.JTextArea();
        fotoPanel = new javax.swing.JPanel();
        jLabel13 = new javax.swing.JLabel();
        deletarButton = new javax.swing.JButton();
        inserirButton = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        novoButton = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        salvarButton = new javax.swing.JButton();
        fecharButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setPreferredSize(new java.awt.Dimension(400, 40));
        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel9.setBackground(new java.awt.Color(255, 255, 255));
        jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        msgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/cadeira_32.png"))); // NOI18N
        msgLabel.setText("msg");
        jPanel9.add(msgLabel);

        jPanel1.add(jPanel9, java.awt.BorderLayout.CENTER);

        jPanel10.setBackground(new java.awt.Color(255, 255, 255));
        jPanel10.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 1, 1, 1));

        ativoCheckBox.setBackground(new java.awt.Color(227, 221, 221));
        ativoCheckBox.setText("Ativo");
        jPanel10.add(ativoCheckBox);

        jPanel1.add(jPanel10, java.awt.BorderLayout.LINE_END);

        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Info. Básicas", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12))); // NOI18N

        jLabel1.setText("ID supervisor:");

        idTextField.setEditable(false);
        idTextField.setFocusable(false);

        jLabel2.setText("Nome:");

        jLabel14.setText("CPF:");

        try {
            cpfTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        cpfTextField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);

        jLabel15.setText("Data de aniversário:");

        try {
            dataAniversarioTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        jLabel3.setText("Telefone empresa:");

        try {
            telefone1TextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("## - ####.####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        telefone1TextField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);

        jLabel4.setText("Telefone pessoal:");

        try {
            telefone2TextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("## - ####.####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        telefone2TextField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);

        jLabel12.setText("E-mail:");

        jLabel16.setText("RG:");

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGap(45, 45, 45)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel12)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel15)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(idTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addComponent(nomeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 387, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel14)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cpfTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel16)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rgTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE))
                    .addComponent(dataAniversarioTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(telefone2TextField, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(telefone1TextField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(emailTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(idTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(nomeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel14)
                    .addComponent(cpfTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel16)
                    .addComponent(rgTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(dataAniversarioTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(telefone1TextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(telefone2TextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(emailTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Endereço", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12))); // NOI18N

        jLabel6.setText("Código postal (CEP):");

        jLabel7.setText("Logradouro:");

        jLabel8.setText("Nº, complemento:");

        jLabel9.setText("Estado:");

        jLabel10.setText("Cidade:");

        jLabel11.setText("Bairro:");

        try {
            cepTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#####-###")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        cepTextField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        cepTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cepTextFieldActionPerformed(evt);
            }
        });

        try {
            estadoTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("UU")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel7Layout.createSequentialGroup()
                        .addGap(43, 43, 43)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel8)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(complementoTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 695, Short.MAX_VALUE)
                            .addGroup(jPanel7Layout.createSequentialGroup()
                                .addComponent(cepTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(logradouroTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 461, Short.MAX_VALUE))))
                    .addGroup(jPanel7Layout.createSequentialGroup()
                        .addGap(115, 115, 115)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel11)
                            .addComponent(jLabel10)
                            .addComponent(jLabel9))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(bairroTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(estadoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cidadeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cepTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(logradouroTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(complementoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bairroTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cidadeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(estadoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Info. Adicionais", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12))); // NOI18N

        jLabel5.setText("Observações:");

        obsTextArea.setColumns(20);
        obsTextArea.setLineWrap(true);
        obsTextArea.setRows(5);
        obsTextArea.setWrapStyleWord(true);
        scrollpane.setViewportView(obsTextArea);

        fotoPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        fotoPanel.setLayout(new java.awt.BorderLayout());

        jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel13.setText("FOTO");
        fotoPanel.add(jLabel13, java.awt.BorderLayout.CENTER);

        deletarButton.setBackground(new java.awt.Color(255, 153, 153));
        deletarButton.setText("DEL");
        deletarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deletarButtonActionPerformed(evt);
            }
        });

        inserirButton.setBackground(new java.awt.Color(204, 204, 255));
        inserirButton.setText("INS");
        inserirButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inserirButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel8Layout.createSequentialGroup()
                        .addComponent(scrollpane, javax.swing.GroupLayout.PREFERRED_SIZE, 642, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(fotoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(inserirButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(deletarButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(jLabel5))
                .addContainerGap())
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel8Layout.createSequentialGroup()
                        .addGap(98, 98, 98)
                        .addComponent(inserirButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deletarButton))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel8Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(fotoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE)
                            .addComponent(scrollpane, javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE))))
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        jPanel3.setLayout(new java.awt.BorderLayout());

        novoButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/plus_16.png"))); // NOI18N
        novoButton.setMnemonic('n');
        novoButton.setText("Novo Supervisor");
        novoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                novoButtonActionPerformed(evt);
            }
        });
        jPanel4.add(novoButton);

        jPanel3.add(jPanel4, java.awt.BorderLayout.LINE_START);

        salvarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/salvar.png"))); // NOI18N
        salvarButton.setMnemonic('s');
        salvarButton.setText("Salvar");
        salvarButton.setPreferredSize(new java.awt.Dimension(120, 26));
        salvarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salvarButtonActionPerformed(evt);
            }
        });
        jPanel5.add(salvarButton);

        fecharButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/delete.png"))); // NOI18N
        fecharButton.setText("Fechar (ESC)");
        fecharButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fecharButtonActionPerformed(evt);
            }
        });
        jPanel5.add(fecharButton);

        jPanel3.add(jPanel5, java.awt.BorderLayout.LINE_END);

        getContentPane().add(jPanel3, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void salvarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salvarButtonActionPerformed
        try {
            this.validarEntradaDoUsuario();

            ControleSupervisor controle = new ControleSupervisor();
            Supervisor b = this.getSupervisor();
            if (isNovoSupervisor()) {
                controle.adicionar(b);
                msgLabel.setText("O supervisor foi salvo com sucesso");
                refresh(true);
            } else {
                controle.atualizar(b);
                msgLabel.setText("Os dados do supervisor foram atualizados com sucesso");
                refresh(true);
            }
        } catch (InputValidationException ivex) {
            msgLabel.setText(ivex.getMessage());
            System.out.println(ivex.getMessage());
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }//GEN-LAST:event_salvarButtonActionPerformed

    private void fecharButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fecharButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_fecharButtonActionPerformed

    private void novoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_novoButtonActionPerformed
        setSupervisor(new Supervisor());
        setNovoSupervisor(true);
    }//GEN-LAST:event_novoButtonActionPerformed

    private void inserirButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inserirButtonActionPerformed
        if (fc == null) {
            fc = new JFileChooser();
            //Add a custom file filter and disable the default
            fc.addChoosableFileFilter(new ImageFilter());
            fc.setAcceptAllFileFilterUsed(false);
        }

        int returnVal = fc.showDialog(SupervisorDialog.this,
                "Anexar Foto...");

        //Process the results.
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                // cria um objeto do tipo BufferedImage do arquivo selecionado...
                File file = fc.getSelectedFile();
                if (foto == null) {
                    foto = new Foto();
                }
                foto.setImagem(ImageIO.read(new File(file.getAbsolutePath())));
                exibeFoto(foto);
                System.out.println("O usuário escolheu a foto: " + file.getName() + ".");
                fc.setSelectedFile(null);
            } catch (IOException ioex) {
                JOptionPane.showMessageDialog(this, "Não foi possível ler a imagem.", "Erro", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            System.out.println("O usuário cancelou o anexo da foto.");
        }

        //Reset the file chooser for the next time it's shown.
        fc.setSelectedFile(null);
    }//GEN-LAST:event_inserirButtonActionPerformed

    private void deletarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deletarButtonActionPerformed
        deletarFoto();
    }//GEN-LAST:event_deletarButtonActionPerformed

    private void cepTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cepTextFieldActionPerformed
        buscaCep();
    }//GEN-LAST:event_cepTextFieldActionPerformed

    private JButton getCepButton() {
        cepTextField.setLayout(new BorderLayout());
        buscarCepButton = new JButton(ImageUtils.createIcon("search16.png"));
        buscarCepButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        buscarCepButton.setToolTipText("Informe o CEP e clique para buscar o logradouro");

        buscarCepButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                buscaCep();
            }
        });

        return buscarCepButton;
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                SupervisorDialog dialog = new SupervisorDialog(new javax.swing.JFrame(), "TBP - Supervisor", true);
                dialog.setSupervisor(new Supervisor());
                dialog.setNovoSupervisor(true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // <editor-fold defaultstate="collapsed" desc="Declaration of class members">
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox ativoCheckBox;
    private javax.swing.JTextField bairroTextField;
    private javax.swing.JFormattedTextField cepTextField;
    private javax.swing.JTextField cidadeTextField;
    private javax.swing.JTextField complementoTextField;
    private javax.swing.JFormattedTextField cpfTextField;
    private javax.swing.JFormattedTextField dataAniversarioTextField;
    private javax.swing.JButton deletarButton;
    private javax.swing.JTextField emailTextField;
    private javax.swing.JFormattedTextField estadoTextField;
    private javax.swing.JButton fecharButton;
    private javax.swing.JPanel fotoPanel;
    private javax.swing.JTextField idTextField;
    private javax.swing.JButton inserirButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JTextField logradouroTextField;
    private javax.swing.JLabel msgLabel;
    private javax.swing.JTextField nomeTextField;
    private javax.swing.JButton novoButton;
    private javax.swing.JTextArea obsTextArea;
    private javax.swing.JTextField rgTextField;
    private javax.swing.JButton salvarButton;
    private javax.swing.JScrollPane scrollpane;
    private javax.swing.JFormattedTextField telefone1TextField;
    private javax.swing.JFormattedTextField telefone2TextField;
    // End of variables declaration//GEN-END:variables
    // </editor-fold>

    public boolean isNovoSupervisor() {
        return novoSupervisor;
    }

    public void setNovoSupervisor(boolean n) {
        this.novoSupervisor = n;
        if (isNovoSupervisor()) {
            msgLabel.setText("Forneça os dados para o novo supervisor");
        } else {
            msgLabel.setText("Visualização dos dados do supervisor " + this.supervisor.getNome());
        }
        nomeTextField.requestFocus();
    }

    public void validarEntradaDoUsuario() throws InputValidationException {
        if (nomeTextField.getText().isEmpty()) {
            nomeTextField.requestFocus();
            throw new InputValidationException("O nome do supervisor deve ser informado");
        }
    }

    public boolean refresh() {
        return refresh;
    }

    public void refresh(boolean r) {
        this.refresh = r;
    }

    public Supervisor objetoSupervisor() {
        return this.supervisor;
    }

    public void mostraEndereco(Endereco e) {
        if (e != null) {
            this.objetoSupervisor().setEndereco(e);
            cepTextField.setText(e.getCep());
            logradouroTextField.setText(e.getLougradouro());
            bairroTextField.setText(e.getBairro());
            cidadeTextField.setText(e.getCidade());
            estadoTextField.setText(e.getEstado());
            complementoTextField.setText(e.getComplemento());
            complementoTextField.requestFocus();
        } else {
            limpaEndereco();
        }
    }

    private void limpaEndereco() {
        this.objetoSupervisor().setEndereco(null);
        logradouroTextField.setText(null);
        bairroTextField.setText(null);
        cidadeTextField.setText(null);
        estadoTextField.setText(null);
        complementoTextField.setText(null);
    }

    public Supervisor getSupervisor() {
        supervisor.setNome(nomeTextField.getText());
        supervisor.setCpf(cpfTextField.getText());
        supervisor.setRg(rgTextField.getText());
        supervisor.setDataDeAniversario(DateUtils.dataStringParaObjeto(dataAniversarioTextField.getText()));
        supervisor.setTelefone1(telefone1TextField.getText());
        supervisor.setTelefone2(telefone2TextField.getText());
        supervisor.setEmail(emailTextField.getText());

        if (supervisor.getEndereco() != null) {
            supervisor.getEndereco().setComplemento(complementoTextField.getText());
        }
        supervisor.setObservacoes(obsTextArea.getText());
        if (foto != null) {
            supervisor.setFoto(this.foto);
        }
        supervisor.setAtivo(ativoCheckBox.isSelected());
        return supervisor;
    }

    public void setSupervisor(Supervisor b) {
        this.supervisor = b;
        ativoCheckBox.setSelected(b.isAtivo());
        idTextField.setText("" + b.getId());
        nomeTextField.setText(b.getNome());
        cpfTextField.setText(b.getCpf());
        rgTextField.setText(b.getRg());
        dataAniversarioTextField.setText(DateUtils.dataObjetoParaString(b.getDataDeAniversario()));
        telefone1TextField.setText(b.getTelefone1());
        telefone2TextField.setText(b.getTelefone2());
        emailTextField.setText(b.getEmail());

        this.mostraEndereco(b.getEndereco());

        obsTextArea.setText(b.getObservacoes());
        obsTextArea.setCaretPosition(0);

        this.exibeFoto(b.getFoto());

        if (!nomeTextField.isFocusOwner()) {
            nomeTextField.requestFocus();
        }
    }

    private void exibeFoto(Foto foto) {
        if (foto == null) {
            deletarFoto();
            return;
        }
        // inicia o processo para reescrever o método paintComponent do JPanel...
        if (jImagePanel == null) {
            jImagePanel = new JImagePanel(foto.getImagem());
            jImagePanel.setFillType(JImagePanel.FillType.RESIZE);
        }
        /*
        try {
        ImageIO.write(foto.getImagem(), "jpg", new File("ithim.jpg"));
        } catch(IOException ioex) {
        System.out.println(ioex.getMessage());
        }
         */
        fotoPanel.removeAll();
        jImagePanel.setImage(foto.getImagem());
        fotoPanel.add(jImagePanel);
        fotoPanel.repaint();
        fotoPanel.validate();
    }

    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                fecharButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }

    private void deletarFoto() {
        fotoPanel.removeAll();
        if (foto != null) {
            foto = null;
            jImagePanel = null;
        }
        fotoPanel.add(new JLabel("FOTO", JLabel.CENTER));
        fotoPanel.repaint();
        fotoPanel.validate();
    }

    private void buscaCep() {
        String cep = cepTextField.getText().replace("-", "");
        ControleEndereco controle = new ControleEndereco();
        try {
            List<Endereco> enderecoList = controle.pesquisar(cep);
            if(enderecoList.isEmpty()) {
                mostraEndereco(null);
            } else {
                mostraEndereco(controle.pesquisar(cep).get(0));
            }
        } catch (PersistenciaException pe) {
            System.out.println(pe.getMessage());
        }
    }
}
